package com.geekbing.elklog.util.verify;

import com.geekbing.elklog.util.response.ResultCode;
import com.geekbing.elklog.util.response.ServiceException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;

/**
 * @author bing
 */
public class ValidationUtil {
    /**
     * 验证参数
     */
    public static void validate(BindingResult result) {
        if (result.hasErrors()) {
            // 获取第一个字段错误
            FieldError error = getFirstFieldError(result.getFieldErrors());
            // 抛出业务异常
            throw new ServiceException(ResultCode.FAIL, error.getDefaultMessage());
        }
    }

    /**
     * 根据字段排序，返回字段名称最小的字段错误
     */
    private static FieldError getFirstFieldError(List<FieldError> errors) {
        FieldError first = errors.get(0);
        for (FieldError error : errors) {
            if (error.getField().compareTo(first.getField()) < 0) {
                first = error;
            }
        }
        return first;
    }
}
